package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import modelDB.Member;

public class MemberDAO implements Manageable<Member, Integer>{

	private EntityManager entityManager;

	public MemberDAO() {
		entityManager = DatabaseConnector.getEntityManager();
	}
	
	@Override
	public boolean insert(Member obj) {
		try {
			entityManager.getTransaction().begin();
			entityManager.persist(obj);
			entityManager.getTransaction().commit();
			
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public boolean update(Member newMem) {
		try {
			entityManager.getTransaction().begin();
			
			Member member = entityManager.find(Member.class, newMem.getId());
			if(member != null) {
				member.setName(newMem.getName());
				//.........
				//TODO Viết tiếp mấy cái set, get vô đây
			}
			
			entityManager.getTransaction().commit();
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public boolean delete(Integer id) {
		try {
			entityManager.getTransaction().begin();
			
			Member member = entityManager.find(Member.class, id);
			if (member != null) {
				entityManager.remove(member);
			}
			
			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public List<Member> selectAll() {
		Query query = entityManager.createQuery("SELECT m FROM Member m");
		return query.getResultList();
	}

	@Override
	public Member findByID(Integer id) {
		return entityManager.find(Member.class, id);
	}

}
